<?php

namespace app\admin\service;

use app\admin\model\MarketingUsers as MarketingUsersModel;

class MarketingUsersService
{
    /**
     * 活动用户列表
     * @param $where
     * @param $page
     * @param $pagesize
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getMarketingUsers($where, $page, $pagesize)
    {
        $list = MarketingUsersModel::getMarketingUsers($where, $page, $pagesize);
        foreach ($list as $k => $v) {
            // 头像/昵称
            $headimg = '<div><img class="headimgs" title="点我查看原图" onclick="lookimg(this.src)" src="' . $v['headimg'] . '" \' + \'alt=""></div>';
            $list[$k]['nickname_data'] = '<div class="d-fix1 mar-lefts">' . $headimg . '<div><p class="datas">' . emojiDecode($v['nickname']) . '</p>';

            // 序号/身份
            $iname = $v['iname'] ?: '游客';
            $list[$k]['identity_data'] = $v['id'] . '<br><span class="color3">' . $iname . '</span>';

            // 角色/来源
            $role = getRoleName($v['role']);
            // 1公众号  2小程序
            $associate = $v['associate'] == 1 ? '公众号' : '小程序';
            $list[$k]['user_type'] = $role . '<br><span class="color3">' . $associate . '</span>';

            // 访问时间/活动来源
            $create_time = date('Y-m-d H:i', strtotime($v['create_time']));
            // 查询活动标题
            $marketing = MarketingService::findMarketing(['id' => $v['mid']]);
            // 查询活动经办人
            $official = OfficialStaffService::findOfficialStaffValue(['id' => $marketing['manager']], 'alias');
            $list[$k]['date_source'] = $create_time . '<br><span class="color3">' . $official . ':' . $marketing['title'] . '</span>';

            $list[$k]['pay_data'] = '-/-';
            // 转换用户列表数据
            if ($v['is_convert']) {
                $list[$k]['pay_data'] = OrderService::getConvertMarketingOrder(['o.marketing_id' => $v['mid'], 'o.uid' => $v['uid']]);
            }

        }

        return $list;
    }

    /**
     * 活动用户统计
     * @param $where
     * @return int
     */
    public static function countMarketingUsers($where)
    {
        return MarketingUsersModel::countMarketingUsers($where);
    }

    /**
     * 活动金额累计
     * @param $where
     * @param string $field
     * @return float
     */
    public static function sumMarketingUsersPrice($where = [], $field = 'money')
    {
//        return MarketingUsersModel::sumMarketingUsersPrice($where, $field);
        return OrderService::sumMarketingOrderPrice($where);
    }

    /**
     * 过去7天活动金额
     * @param $where
     * @return float
     */
    public static function getMarketingUsersPriceLine($where = [])
    {
        $startEndTime = getStartEndTime(6);
//        $marketingUsersPrice = MarketingUsersModel::getMarketingUsersPrice($where, $startEndTime['startTime'], $startEndTime['endTime'], $field);
        $marketingUsersPrice = OrderService::getMarketingOrderPrice($startEndTime['startTime'], $startEndTime['endTime'], $where);
        return inArr($marketingUsersPrice, $startEndTime['dateArr']);
    }

    /**
     * 所有端活动用户总数
     * @param $where
     * @return int
     */
    public static function totalAllMarketingUsers($where)
    {
        return MarketingUsersModel::totalAllMarketingUsers($where);
    }

    /**
     * 指定端活动用户总数
     * @param $where
     * @return int
     */
    public static function totalOtherMarketingUsers($where)
    {
        return MarketingUsersModel::totalOtherMarketingUsers($where);
    }

    /**
     * 今日活动用户
     * @param $where
     * @return int
     */
    public static function todayMarketingUsers($where)
    {
        return MarketingUsersModel::todayMarketingUsers($where);
    }

    /**
     * 昨日活动用户
     * @param $where
     * @return int
     */
    public static function yesTodayMarketingUsers($where)
    {
        return MarketingUsersModel::yesTodayMarketingUsers($where);
    }

    /**
     * 本月活动用户
     * @param $where
     * @return int
     */
    public static function monthMarketingUsers($where)
    {
        return MarketingUsersModel::monthMarketingUsers($where);
    }

    /**
     * 部门直属用户
     * @param $types
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getDepartmentDirectUsers($types = 3)
    {
        $data = OfficialStaffService::getOfficialStaff($types);
        $underNums = 0;
        $usersList = [];
        foreach ($data as $k => $v) {
            $usersNums = self::countMarketingUsers(['m.manager' => $v['id']]);
            $usersList[$k]['name'] = $v['alias'];
            $usersList[$k]['usersNums'] = $usersNums;
            $underNums += $usersNums;
        }

        return ['underNums' => $underNums, 'usersList' => $usersList];
    }

    /**
     * 其他活动用户
     * @return array
     */
    public static function otherMarketingUsers()
    {
        $data = MarketingUsersModel::otherMarketingUsers();
        $sourceNums = 0;
        foreach ($data as $k => $v) {
            $data[$k]['source'] = $v['associate'] == 1 ? 'H5' : '小程序';
            $sourceNums += $v['usersNums'];
        }

        // 默认值
        if (!$data) {
            $data[1]['usersNums'] = $data[0]['usersNums'] = 0;
            $data[0]['source'] = 'H5';
            $data[1]['source'] = '小程序';
        }

        return ['sourceNums' => $sourceNums, 'usersList' => $data];
    }

    /**
     * 本月活动用户（折线图）
     * @return mixed
     */
    public static function getMarketingUsersMonthLine()
    {
        $startEndTime = getStartEndTime();
        $marketingMonth = MarketingUsersModel::getMarketingUsersLine($startEndTime['startTime'], $startEndTime['endTime']);
        return inArr($marketingMonth, $startEndTime['dateArr']);
    }

    /**
     * 过去7天活动订单（折线图）
     * @param $where
     * @return mixed
     */
    public static function getMarketingOrderLine($where)
    {
        return self::getMarketingUsersPriceLine($where);
//        $startEndTime = getStartEndTime(6);
//        $marketingUsersPrice = MarketingUsersModel::getMarketingUsersPrice($where, $startEndTime['startTime'], $startEndTime['endTime']);
//        return inArr($marketingUsersPrice, $startEndTime['dateArr']);
    }

    /**
     * 活动订单营业额
     * @param $where
     * @param int $types
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getMarketingOrderPrice($where, $types = 3)
    {
        $underPrice = 0;
        $usersList = [];
        // 指定用户活动营业额
        if (isset($where['manager'])) {
            $underPrice = self::sumMarketingUsersPrice($where);
        } else {
            $data = OfficialStaffService::getOfficialStaff($types);
            foreach ($data as $k => $v) {
                $where['manager'] = $v['id'];
                $price = self::sumMarketingUsersPrice($where);
                $usersList[$k]['name'] = $v['alias'];
                $usersList[$k]['price'] = $price;
                $underPrice += $price;
            }
        }

        return ['underPrice' => $underPrice, 'usersList' => $usersList];
    }

    /**
     * 下单地区分布
     * @param $where
     * @return array
     */
    public static function getMarketingOrderArea($where)
    {
//        $data = MarketingUsersModel::getMarketingOrderArea($where, 0, 3);
        $data = OrderService::getMarketingOrderArea($where, 0, 3);
        $datas = [];
        foreach ($data as $k => $v) {
            $datas[] = json_encode([
                'name' => $v['name'],
                'value' => $v['nums'],
            ], JSON_UNESCAPED_UNICODE);
        }
        $datas = join(';', $datas);
        // 剩余其他地区分布
        $lastData = OrderService::getMarketingOrderArea($where, 3, 99);
        // 下单地区总数
        $totalArea = OrderService::totalMarketingOrderArea($where);

        return ['count' => count($data), 'datas' => $datas, 'lastData' => $lastData, 'totalArea' => $totalArea];
    }

    /**
     * 下单身份数据
     * @param $where
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getMarketingOrderIdentity($where)
    {
        $peopleList = MarketingUsersModel::getMarketingOrderIdentity($where);
        return getIdentityData($peopleList, 1, 1);
    }
}